<?php

namespace app\batch;

use think\Db;

use think\console\Command;
use app\facade\Redis;
use think\console\Input;
use think\console\Output;
use app\models\{Autoorder, Order, OrderProduct, Agent, AgentArea, Product, Riderlist, RiderStreet};

class AutoOrders extends Command
{
    protected $open = false;
    protected function configure()
    {
        $this->setName('AutoOrders')->setDescription('刷单');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        die();
    }

    protected function doCron()
    {
        $time = date('H');
        if ($time < 8 || $time > 21) {
            echo '没有到刷单时间';
            die;
        }
        // $saves = [];
        // for ($i=0; $i < 10000; $i++) { 
        //     $saves[] = [
        //         'type' => 5,
        //         'province' => 430000,
        //         'city' => 430100,
        //         'area' => 430121,
        //         'street' => 25749,
        //         'ploygongeo' => 'POLYGON((113.079067 28.289327,113.143457 28.376444,113.144661 28.376745,113.162955 28.355847,113.182224 28.334136,113.216017 28.295266,113.281187 28.304372,113.252987 28.236817,113.096101 28.227339,113.079067 28.289327))',
        //         'agentid' => 28
        //     ];
        // }
        // if(count($saves) > 0){
        //     (new AgentArea())->allowfield(true)->saveAll($saves);

        // }
        // $str = "江苏盐城、安徽临泉县、福建晋江市、湖南固始、江苏溧阳、广东江门开平市、湛江坡头区、湛江吴川市、湖南古丈县、湖南双峰县、湖南郴州、湖南常德、湖北仙桃、湖北通城、江西抚州、四川资阳、贵州毕节、重庆渝北、郑州金水、郑州登封";

        // dump($str);
        // $starr = explode('、',$str);
        // foreach ($starr as $starrs) {
        //     $have = (new Agent())->where('nickname',$starrs)->find();
        //     if(empty($have)){
        //         (new Agent())->insertGetId([
        //             'accounts' => rand(),
        //             'mobile' => '176730'.rand(11111,99999),
        //             'password' => md5('a123456'),
        //             'title' => $starrs,
        //             'nickname' => $starrs,
        //         ]);
        //     }
        // }
        // (new Autoorder())->where(['status' => 1, 'type' => 3])->chunk(20, function ($list) {
        //     //查询下级订单的总重
        //     foreach ($list as $lists) {
        //         $color = ['白色', '黑色', '白色', '黑色', '白色', '黑色', '灰色', '灰色', '银色', '银色', '蓝色', '红色'];
        //         //先查找上次记录
        //         $address = json_decode($lists['parpam'], true) ?? [];
        //         $status = 4;
        //         $countrand = 1;
        //         $orderall = [];
        //         $orderproductall = [];
        //         $rdsname = 'wtxcauto2listbs333' . $lists['agentid'] . $countrand;
        //         $frtimes = Redis::get($rdsname);
        //         if ($frtimes) {
        //             echo '跳过' . date('Y-m-d H:i:s');
        //             continue;
        //         } else {
        //             Redis::setex($rdsname, 120, 120);
        //         }
        //         $time =  strtotime(date('Y-m-d', time())) - $countrand * 86400 + rand(28800, 79200); //30天内订单
        //         //获取当天的数据量
        //         $ystdate = date('Y-m-d H:i:s', strtotime(date('Y-m-d', $time)));
        //         $tstdate = date('Y-m-d H:i:s', strtotime(date('Y-m-d', $time + 86400)));
        //         $counts = (new Order())->whereBetweenTime('created', $ystdate, $tstdate)->where('agentid', $lists['agentid'])->count();
        //         if ($counts >= 440) {
        //             continue;
        //         }
        //         //需要刷的数量
        //         $shuanumber = 440 - $counts;
        //         for ($i = 0; $i < $shuanumber; $i++) {
        //             if ($countrand == 0) {
        //                 $status = rand(2, 4);
        //             }
        //             $counts = (new Order())->whereBetweenTime('created', $ystdate, $tstdate)->where('agentid', $lists['agentid'])->count();
        //             if ($counts >= 440) {
        //                 continue;
        //             }
        //             $number = rand(0, count($address) - 1);
        //             $order = [
        //                 'user_id' => 1,
        //                 'ordersn' => reordersn(new Order()),
        //                 'agentid' => $lists['agentid'],
        //                 'name' => $address[$number]['name'] ?? '',
        //                 'mobile' => $address[$number]['mobile'] ?? '',
        //                 'province' =>  $lists['province'],
        //                 'city' =>  $lists['city'],
        //                 'area' =>  $lists['area'],
        //                 'street' =>  $lists['street'],
        //                 'posaddress' => '',
        //                 'cardstype' => rand(1, 2),
        //                 'keyss' => $data['keyss'] ?? '电话联系取送钥匙',
        //                 'cards' => '',
        //                 'model' => rand(1, 2) ?? 1,
        //                 'color' => $color[rand(0, 4)] ?? '',
        //                 'address' => '',
        //                 'lat' => 113.108410,
        //                 'lon' => 28.212606,
        //                 'appointment' => date('Y-m-d H:i:s', $time + 1800 + rand(60, 1800)),
        //                 'info' => $data['info'] ?? '',
        //                 'status' => 1,
        //                 'coupon' => 0,
        //                 'cmoney' => 0,
        //                 'dict' => 100,
        //                 'payment' => 1,
        //                 'ptotal' => 0,
        //                 'status' => $status,
        //                 'created' => date('Y-m-d H:i:s', $time),
        //                 'ccount' => 0,
        //                 'dicttotal' => 0,
        //                 'total' => 0,
        //                 'income' => 2,
        //                 'message' => 2,
        //                 'issystem' => 2
        //             ];
        //             $order['orderid'] = 0;
        //             $order['ordertime'] = date('Y-m-d H:i:s', $time + rand(60, 1800));
        //             $limit = 1;
        //             $orderproduct = [];
        //             $product = (new Product())->orderRaw("rand()")->where('price', '<=', 40)->limit($limit)
        //                 ->where(['isdel' => 1, 'isshow' => 1, 'agentid' => 0])->select();
        //             foreach ($product as $products) {
        //                 //查找下面有没有相关服务人员
        //                 $products['number'] = 1;
        //                 $orderproduct[] = [
        //                     'ordersn' => $order['ordersn'],
        //                     'agentid' => $lists['agentid'],
        //                     'cate' => $products['cate'],
        //                     'productid' => $products['id'],
        //                     'title' =>  $products['title'],
        //                     'descs' =>  $products['descs'],
        //                     'images' =>  $products['images'],
        //                     'price' =>  $products['price'],
        //                     'number' =>  $products['number'],
        //                     'type' => $products['type'],
        //                     'cnumber' => 0,
        //                     'cid' => 0,
        //                 ];
        //                 $order['ptotal'] += floor($products['number'] * $products['price'] * 1000) / 1000;
        //             }
        //             $order['dicttotal'] = $order['ptotal'];
        //             $order['total'] = round(($order['ptotal']), 2);
        //             if ($order['total'] <= 0) {
        //                 $order['total'] = 0;
        //             }
        //             $orderall[] = $order;
        //             $orderproductall[] = $orderproduct;
        //         }
        //         if (count($orderall) > 0 && count($orderproductall) > 0) {
        //             (new Order())->allowfield(true)->saveAll($orderall);
        //             (new OrderProduct())->allowfield(true)->saveAll($orderproduct);
        //         }
        //     }
        // });
        // (new Autoorder())->where(['status' => 1, 'type' => 2])->chunk(20, function ($list) {
        //     //查询下级订单的总重
        //     foreach ($list as $lists) {
        //         $color = ['白色', '黑色', '白色', '黑色', '白色', '黑色', '灰色', '灰色', '银色', '银色', '蓝色', '红色'];
        //         //先查找上次记录
        //         $address = json_decode($lists['parpam'], true) ?? [];
        //         $status = 4;
        //         for ($countrand = 0; $countrand <= 0; $countrand++) {
        //             $orderall = [];
        //             $orderproductall = [];
        //             $rdsname = 'wtxcauto2listbs2' . $lists['agentid'] . $countrand;
        //             $frtimes = Redis::get($rdsname);
        //             if ($frtimes) {
        //                 echo '跳过' . date('Y-m-d H:i:s');
        //                 continue;
        //             } else {
        //                 Redis::setex($rdsname, 120, 120);
        //             }
        //             if ($countrand <= 0) {
        //                 $time =  time(); //30天内订单
        //                 //获取当天的数据量
        //                 $ystdate = date('Y-m-d H:i:s', strtotime(date('Y-m-d', $time)));
        //                 $tstdate = date('Y-m-d H:i:s', strtotime(date('Y-m-d', $time + 86400)));
        //                 $counts = (new Order())->whereBetweenTime('created', $ystdate, $tstdate)->where('agentid', $lists['agentid'])->count();
        //                 $numberssssss = (date('H') - 8) * 18 + $lists['agentid'];
        //                 if ($counts >= $numberssssss) {
        //                     continue;
        //                 }
        //                 //需要刷的数量
        //                 $shuanumber = $numberssssss  - $counts + $lists['agentid'];
        //                 if ($time > time()) {
        //                     continue;
        //                 }
        //             } else {
        //                 $time =  strtotime(date('Y-m-d', time())) - $countrand * 86400 + rand(28800, 79200); //30天内订单
        //                 //获取当天的数据量
        //                 $ystdate = date('Y-m-d H:i:s', strtotime(date('Y-m-d', $time)));
        //                 $tstdate = date('Y-m-d H:i:s', strtotime(date('Y-m-d', $time + 86400)));
        //                 $counts = (new Order())->whereBetweenTime('created', $ystdate, $tstdate)->where('agentid', $lists['agentid'])->count();
        //                 if ($counts >= (220 + $countrand + $lists['agentid'])) {
        //                     continue;
        //                 }
        //                 //需要刷的数量
        //                 $shuanumber = 220 + $countrand - $counts + $lists['agentid'];
        //             }
        //             for ($i = 0; $i < $shuanumber; $i++) {
        //                 if ($countrand == 0) {
        //                     $status = rand(2, 4);
        //                 }
        //                 $counts = (new Order())->whereBetweenTime('created', $ystdate, $tstdate)->where('agentid', $lists['agentid'])->count();
        //                 if ($counts >= (220 + $countrand + $lists['agentid'])) {
        //                     continue;
        //                 }
        //                 $number = rand(0, count($address) - 1);
        //                 $order = [
        //                     'user_id' => 1,
        //                     'ordersn' => reordersn(new Order()),
        //                     'agentid' => $lists['agentid'],
        //                     'name' => $address[$number]['name'] ?? '',
        //                     'mobile' => $address[$number]['mobile'] ?? '',
        //                     'province' =>  $lists['province'],
        //                     'city' =>  $lists['city'],
        //                     'area' =>  $lists['area'],
        //                     'street' =>  $lists['street'],
        //                     'posaddress' => '',
        //                     'cardstype' => rand(1, 2),
        //                     'keyss' => $data['keyss'] ?? '电话联系取送钥匙',
        //                     'cards' => '',
        //                     'model' => rand(1, 2) ?? 1,
        //                     'color' => $color[rand(0, 4)] ?? '',
        //                     'address' => '',
        //                     'lat' => 113.108410,
        //                     'lon' => 28.212606,
        //                     'appointment' => date('Y-m-d H:i:s', $time + 1800 + rand(60, 1800)),
        //                     'info' => $data['info'] ?? '',
        //                     'status' => 1,
        //                     'coupon' => 0,
        //                     'cmoney' => 0,
        //                     'dict' => 100,
        //                     'payment' => 1,
        //                     'ptotal' => 0,
        //                     'status' => $status,
        //                     'created' => date('Y-m-d H:i:s', $time),
        //                     'ccount' => 0,
        //                     'dicttotal' => 0,
        //                     'total' => 0,
        //                     'income' => 2,
        //                     'message' => 2,
        //                     'issystem' => 2
        //                 ];
        //                 $order['orderid'] = 0;
        //                 $order['ordertime'] = date('Y-m-d H:i:s', $time + rand(60, 1800));
        //                 $limit = 1;
        //                 $orderproduct = [];
        //                 $product = (new Product())->orderRaw("rand()")->where('price', '<=', 40)->limit($limit)
        //                     ->where(['isdel' => 1, 'isshow' => 1, 'agentid' => 0])->select();
        //                 foreach ($product as $products) {
        //                     //查找下面有没有相关服务人员
        //                     $products['number'] = 1;
        //                     $orderproduct[] = [
        //                         'ordersn' => $order['ordersn'],
        //                         'agentid' => $lists['agentid'],
        //                         'cate' => $products['cate'],
        //                         'productid' => $products['id'],
        //                         'title' =>  $products['title'],
        //                         'descs' =>  $products['descs'],
        //                         'images' =>  $products['images'],
        //                         'price' =>  $products['price'],
        //                         'number' =>  $products['number'],
        //                         'type' => $products['type'],
        //                         'cnumber' => 0,
        //                         'cid' => 0,
        //                     ];
        //                     $order['ptotal'] += floor($products['number'] * $products['price'] * 1000) / 1000;
        //                 }
        //                 $order['dicttotal'] = $order['ptotal'];
        //                 $order['total'] = round(($order['ptotal']), 2);
        //                 if ($order['total'] <= 0) {
        //                     $order['total'] = 0;
        //                 }
        //                 $orderall[] = $order;
        //                 $orderproductall[] = $orderproduct;
        //             }
        //             if (count($orderall) > 0 && count($orderproductall) > 0) {
        //                 (new Order())->allowfield(true)->saveAll($orderall);
        //                 (new OrderProduct())->allowfield(true)->saveAll($orderproduct);
        //             }
        //         }
        //     }
        // });
        //归属地查询更新
        (new Order())->whereNull('gsd')->chunk(10, function ($item) {
            foreach ($item as $items) {
                $rdsname = 'gsdOrdeers' . $items['id'];
                $frtimes = Redis::get($rdsname);
                if ($frtimes) {
                    continue;
                } else {
                    Redis::setex($rdsname, 1800, 1800);
                }
                if ($items['agentid'] == 3) {
                    $gsdtext = '';
                    $gsd = gsdcx($items['mobile']);
                    if (!empty($gsd) && $gsd['ret'] == 200 && !empty($gsd['data']) && !empty($gsd['data']['prov']) && !empty($gsd['data']['city'])) {
                        $gsdtext = $gsd['data']['prov'] . $gsd['data']['city'];
                        if (!empty($gsd['data']['isp'])) {
                            $gsdtext = $gsdtext . '[' . $gsd['data']['isp'] . ']';
                        }
                    }
                    if (!empty($gsd) && ($gsd['ret'] == 40001 || $gsd['ret'] == 40002 || $gsd['ret'] == 40003)) {
                        $gsdtext = '号码错误';
                    }
                    if (!empty($gsdtext)) {
                        (new Order())->where('id', $items['id'])->update(['gsd' => $gsdtext]);
                    }
                } else {
                    (new Order())->where('id', $items['id'])->update(['gsd' => '未知']);
                }
            }
        });

        //太久的订单自动结算
        (new Order())->where(['issystem' => 2, 'status' => [2, 3]])
            ->whereTime('ordertime', '<=', date('Y-m-d H:i:s', time() - 18000))
            ->chunk(10, function ($item) {
                foreach ($item as $items) {
                    (new Order())->where('id', $items['id'])->update(['status' => 4]);
                    echo $items['id'] . '自动结算';
                }
            });
        $riderlist = (new Riderlist())->where(['issystem' => 2])->column('id') ?? [];
        (new Autoorder())->where(['status' => 1, 'type' => 1])->chunk(20, function ($list) use ($riderlist) {
            //查询下级订单的总重
            foreach ($list as $lists) {
                $rdsname = 'AutoOrders' . $lists['id'];
                $cstime = (int)$lists['cstime'] ?? 460;
                $frtimes = Redis::get($rdsname);
                if ($frtimes) {
                    continue;
                } else {
                    Redis::setex($rdsname, $cstime, $cstime);
                }
                if (empty($riderlist)) {
                    $riderlist[] = $lists['rider'];
                }
                $color = ['白色', '黑色', '白色', '黑色', '白色', '黑色', '灰色', '灰色', '银色', '银色', '蓝色', '红色'];
                //先查找上次记录
                $address = json_decode($lists['parpam'], true) ?? [];
                $number = rand(0, count($address) - 1);
                $status = rand(3, 4);
                $order = [
                    'user_id' => 1,
                    'ordersn' => reordersn(new Order()),
                    'agentid' => $lists['agentid'],
                    'name' => $address[$number]['name'] ?? '',
                    'mobile' => $address[$number]['mobile'] ?? '',
                    'province' =>  $lists['province'],
                    'city' =>  $lists['city'],
                    'area' =>  $lists['area'],
                    'street' =>  $lists['street'],
                    'posaddress' => $address[$number]['posaddress'] ?? '',
                    'cardstype' => rand(1, 2),
                    'keyss' => $data['keyss'] ?? '电话联系取送钥匙',
                    'cards' => $address[$number]['cards'] ?? '',
                    'model' => rand(1, 2) ?? 1,
                    'color' => $color[rand(0, 4)] ?? '',
                    'address' => $address[$number]['address'] ?? '',
                    'lat' => 113.108410,
                    'lon' => 28.212606,
                    'appointment' => date('Y-m-d H:i:s', time() + 1800 + rand(60, 1800)),
                    'info' => $data['info'] ?? '',
                    'status' => 1,
                    'coupon' => 0,
                    'cmoney' => 0,
                    'dict' => 100,
                    'payment' => 1,
                    'ptotal' => 0,
                    'status' => $status,
                    'ccount' => 0,
                    'dicttotal' => 0,
                    'total' => 0,
                    'issystem' => 2
                ];
                $ridernumbers = rand(0, count($riderlist) - 1);
                $order['orderid'] = $riderlist[$ridernumbers] ?? 0;
                $order['ordertime'] = date('Y-m-d H:i:s', time() + rand(60, 1800));
                if ($status == 3 || $status == 4) {
                    $order['message'] = 2;
                    if ($status == 4) {
                        $order['endtime'] = date('Y-m-d H:i:s', time() + 7200 + rand(60, 1800));
                    }
                }
                $limit = 1;
                $orderproduct = [];
                $product = (new Product())->orderRaw("rand()")->where('price', '<=', 40)->limit($limit)
                    ->where(['isdel' => 1, 'isshow' => 1, 'agentid' => $lists['agentid']])->select();
                foreach ($product as $products) {
                    //查找下面有没有相关服务人员
                    $products['number'] = 1;
                    $orderproduct[] = [
                        'ordersn' => $order['ordersn'],
                        'agentid' => $lists['agentid'],
                        'cate' => $products['cate'],
                        'productid' => $products['id'],
                        'title' =>  $products['title'],
                        'descs' =>  $products['descs'],
                        'images' =>  $products['images'],
                        'price' =>  $products['price'],
                        'number' =>  $products['number'],
                        'type' => $products['type'],
                        'cnumber' => 0,
                        'cid' => 0,
                    ];
                    $order['ptotal'] += floor($products['number'] * $products['price'] * 1000) / 1000;
                }
                $order['dicttotal'] = $order['ptotal'];
                $order['total'] = round(($order['ptotal']), 2);
                if ($order['total'] <= 0) {
                    $order['total'] = 0;
                }

                if (count($orderproduct) > 0) {
                    Db::startTrans();
                    try {
                        (new Order())->save($order);
                        (new OrderProduct())->allowfield(true)->saveAll($orderproduct);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        echo $e->getMessage();
                    }
                    echo '下单成功';
                }
            }
        });
        (new Autoorder())->where(['status' => 1, 'type' => 2])->chunk(20, function ($list) use ($riderlist) {
            //查询下级订单的总重
            foreach ($list as $lists) {
                $rdsname = 'AutoOrders' . $lists['id'];
                $frtimes = Redis::get($rdsname);
                if ($frtimes) {
                    continue;
                } else {
                    Redis::setex($rdsname, 145, 145);
                }
                if (empty($riderlist)) {
                    $riderlist[] = $lists['rider'];
                }
                $color = ['白色', '黑色', '白色', '黑色', '白色', '黑色', '灰色', '灰色', '银色', '银色', '蓝色', '红色'];
                //先查找上次记录
                $address = json_decode($lists['parpam'], true) ?? [];
                $number = rand(0, count($address) - 1);
                $status = rand(3, 4);
                $order = [
                    'user_id' => 1,
                    'ordersn' => reordersn(new Order()),
                    'agentid' => $lists['agentid'],
                    'name' => $address[$number]['name'] ?? '',
                    'mobile' => $address[$number]['mobile'] ?? '',
                    'province' =>  $lists['province'],
                    'city' =>  $lists['city'],
                    'area' =>  $lists['area'],
                    'street' =>  $lists['street'],
                    'posaddress' => '',
                    'cardstype' => rand(1, 2),
                    'keyss' => $data['keyss'] ?? '电话联系取送钥匙',
                    'cards' => $address[$number]['cards'] ?? '',
                    'model' => rand(1, 2) ?? 1,
                    'color' => $color[rand(0, 4)] ?? '',
                    'address' =>  '',
                    'lat' => 113.108410,
                    'lon' => 28.212606,
                    'appointment' => date('Y-m-d H:i:s', time() + 1800 + rand(60, 1800)),
                    'info' => $data['info'] ?? '',
                    'status' => 1,
                    'coupon' => 0,
                    'cmoney' => 0,
                    'dict' => 100,
                    'payment' => 1,
                    'ptotal' => 0,
                    'status' => $status,
                    'ccount' => 0,
                    'dicttotal' => 0,
                    'message' => 2,
                    'total' => 0,
                    'issystem' => 2
                ];
                $ridernumbers = rand(0, count($riderlist) - 1);
                $order['orderid'] = $riderlist[$ridernumbers] ?? 0;
                $order['ordertime'] = date('Y-m-d H:i:s', time() + rand(60, 1800));
                if ($status == 3 || $status == 4) {
                    $order['message'] = 2;
                    if ($status == 4) {
                        $order['endtime'] = date('Y-m-d H:i:s', time() + 7200 + rand(60, 1800));
                    }
                }
                $limit = 1;
                $orderproduct = [];
                $product = (new Product())->orderRaw("rand()")->where('price', '<=', 40)->limit($limit)
                    ->where(['isdel' => 1, 'isshow' => 1, 'agentid' => 0])->select();
                foreach ($product as $products) {
                    //查找下面有没有相关服务人员
                    $products['number'] = 1;
                    $orderproduct[] = [
                        'ordersn' => $order['ordersn'],
                        'agentid' => $lists['agentid'],
                        'cate' => $products['cate'],
                        'productid' => $products['id'],
                        'title' =>  $products['title'],
                        'descs' =>  $products['descs'],
                        'images' =>  $products['images'],
                        'price' =>  $products['price'],
                        'number' =>  $products['number'],
                        'type' => $products['type'],
                        'cnumber' => 0,
                        'cid' => 0,
                    ];
                    $order['ptotal'] += floor($products['number'] * $products['price'] * 1000) / 1000;
                }
                $order['dicttotal'] = $order['ptotal'];
                $order['total'] = round(($order['ptotal']), 2);
                if ($order['total'] <= 0) {
                    $order['total'] = 0;
                }

                if (count($orderproduct) > 0) {
                    Db::startTrans();
                    try {
                        (new Order())->save($order);
                        (new OrderProduct())->allowfield(true)->saveAll($orderproduct);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        echo $e->getMessage();
                    }
                    echo '下单成功';
                }
            }
        });
    }
}
